package com.iscas.lndicatormonitor.filter;

import com.iscas.lndicatormonitor.utils.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    private JwtTokenUtil jwtTokenUtil;

    public JwtRequestFilter(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        final String requestTokenHeader = request.getHeader("Authorization");
        final String requestUserName = request.getHeader("username");
        String username = null;
        String jwtToken = null;
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);

            // 设置允许哪个源访问
            response.setHeader("Access-Control-Allow-Origin", "*"); // 或者指定的域名，如 "http://example.com"

            // 设置允许的方法
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

            // 设置预检请求的缓存时间（秒）
            response.setHeader("Access-Control-Max-Age", "3600");

            // 设置允许的头部字段
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Authorization,username");

            // 如果需要，可以设置额外的响应头
            // response.setHeader("Access-Control-Expose-Headers", "SomeHeader");
            return;
        }
        // JWT Token 在 "Bearer token" 格式中
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
                if (requestUserName != null && !requestUserName.equals(username)) {
                    return;
                }
            } catch (IllegalArgumentException e) {
                // 处理Token无效的情况
                System.out.println("token无效" + e);
            } catch (ExpiredJwtException e) {
                // 处理Token过期的情况

            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (jwtTokenUtil.validateToken(jwtToken, username)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        new User(username, "", new ArrayList<>()),
                        null, new ArrayList<>());
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}